<template>
  <el-container>
    <el-dialog
      v-model="dialogVisible"
      title="新增操作"
      width="30%"
      center
      draggable
    >
      <el-form
        :model="form"
        class="addform"
        label-width="auto"
        :rules="addrules"
        ref="ruleFormRef"
      >
        <el-form-item label="用户名:" prop="sname">
          <el-input v-model="form.sname" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="年龄:" prop="age">
          <el-input v-model.number="form.age"></el-input>
        </el-form-item>

        <el-form-item label="电话:" prop="phone">
          <el-input v-model.number="form.phone"></el-input>
        </el-form-item>

        <el-form-item label="性别:" prop="gender">
          <el-select
            v-model="form.gender"
            placeholder="选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="职位:" prop="position">
          <el-select
            v-model="form.position"
            placeholder="选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in position"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="工资/日:" prop="salary">
          <el-input v-model.number="form.salary"></el-input>
        </el-form-item>

        <el-form-item label="账号:" prop="account">
          <el-input v-model.number="form.account"></el-input>
        </el-form-item>

        <el-form-item label="密码:" prop="password">
          <el-input v-model.number="form.password"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmadd(form)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="editVisible"
      title="编辑操作"
      width="30%"
      center
      draggable
    >
      <el-form
        ref="editFormRef"
        :model="editform"
        class="addform"
        status-icon
        label-width="auto"
        :rules="editrules"
      >
        <el-form-item label="用户名:" prop="sname">
          <el-input v-model="editform.sname" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="年龄:" prop="age">
          <el-input v-model.number="editform.age"></el-input>
        </el-form-item>

        <el-form-item label="电话:" prop="phone">
          <el-input v-model.number="editform.phone"></el-input>
        </el-form-item>

        <el-form-item label="性别:" prop="gender">
          <el-select
            v-model="editform.gender"
            placeholder="选择性别"
            style="width: 100%"
          >
            <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="职位:" prop="position">
          <el-select
            v-model="editform.position"
            placeholder="选择职位"
            style="width: 100%"
          >
            <el-option
              v-for="item in position"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="工资:" prop="salary">
          <el-input v-model.number="editform.salary"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmedit(editform)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="editpassVisible"
      title="修改密码"
      width="30%"
      center
      draggable
    >
      <el-form
        ref="editpassFormRef"
        :model="editpassform"
        class="editpassform"
        status-icon
        label-width="auto"
        :rules="editpassrules"
      >
        <el-form-item label="输入旧密码:" prop="oldpass">
          <el-input v-model="editpassform.oldpass" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="重复输入旧密码:" prop="repepass">
          <el-input v-model="editpassform.repepass"></el-input>
        </el-form-item>

        <el-form-item label="输入新密码:" prop="newpass">
          <el-input v-model="editpassform.newpass"></el-input>
        </el-form-item>

      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editpassVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmpass(editpassform)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-header class="head">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="input1" placeholder="请输入矿泉水名字">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="2">
          <el-button type="primary" @click="select(input1)">查询</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" @click="dialogVisible = true"
            >新增</el-button
          >
        </el-col>
        <el-col :span="6"></el-col>
        <el-col :span="3"><span>工作人员表</span></el-col>
      </el-row>
    </el-header>

    <el-main class="table-box">
      <el-table
        :data="tableData"
        border
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        @selection-change="changemult"
      >
        <el-table-column type="selection" width="100" />
        <el-table-column
          type="index"
          width="50"
          :index="indexMethod"
          label="编号"
        />
        <el-table-column prop="sname" label="用户名" width="200">
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80"> </el-table-column>
        <el-table-column prop="phone" label="电话" width="150">
        </el-table-column>
        <el-table-column prop="position" label="地址" width="150">
        </el-table-column>
        <el-table-column prop="salary" label="工资/日" width="100">
        </el-table-column>
        <el-table-column label="单项操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              @click="handleEditPass(scope.$index, scope.row)"
              >修改密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <div class="pagin">
      <el-pagination
        layout="prev, pager, next"
        :total="totalNumber"
        :page-size="Pagesize"
        :pager-count="10"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </el-container>
</template>

<script>
import { defineComponent, onMounted, reactive, ref } from "vue";
import {
  getstaff,
  getstaffdata,
  updatestaffbyid,
  updatestaffpass,
  savestaff,
  insertstaff,
  deletestaffbyid,
} from "@/apis/userData.js";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  components: {
    Search,
  },
  data() {
    return {
      options: ["男", "女"],
      position: ["管理员", "送水工", "前台", "工作人员"],
    };
  },

  setup() {
    let multipleSelection = ref([]);
    const input1 = ref("");
    const dialogVisible = ref(false);
    let totalNumber = ref(0);
    let currentPage = ref(1);
    let Pagesize = ref(5);
    let editVisible = ref(false);
    let editpassVisible = ref(false);

    let listdata = ref("");
    let tableData = ref("");

    const form = reactive({
      sid: "",
      sname: "",
      gender: "",
      phone: "",
      position: "",
      age: "",
      salary: "",
      account: "",
      password: "",
    });

    const editform = reactive({
      sid: "",
      sname: "",
      gender: "",
      phone: "",
      position: "",
      age: "",
      salary: "",
    });

    const editpassform = reactive({
      sid: "",
      oldpass: "",
      repepass: "",
      newpass: "",
    });

    const checkpass=(rule,value,callback)=>{
      if(value.trim().length==0){
        callback(new Error("请确认密码不能为空"));
      }else if(value !=editpassform.oldpass){
        callback(new Error("两次密码不一致"));
      }else{
        callback();
      }
    };


    const checkphone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入电话"));
      }
      setTimeout(() => {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        const isPhone = reg.test(value);
        value = Number(value); //转换为数字
        if (typeof value === "number" && !isNaN(value)) {
          //判断是否为数字
          value = value.toString(); //转换成字符串
          if (value.length < 0 || value.length > 12 || !isPhone) {
            //判断是否为11位手机号
            callback(new Error("手机号码格式是11位"));
          } else {
            callback();
          }
        }
      }, 100);
    };

    const addrules = reactive({
      sname: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "blur",
        },
      ],
      age: [
        {
          required: true,
          message: "请输入年龄",
          trigger: "blur",
        },
        { type: "number", message: "类型必须为数字" },
      ],
      phone: [{ validator: checkphone, trigger: "blur" }],
      gender: [
        {
          required: true,
          message: "请选择性别",
          trigger: "blur",
        },
      ],
      position: [
        {
          required: true,
          message: "请选择职位",
          trigger: "blur",
        },
      ],
      account: [
        {
          required: true,
          message: "请输入账号",
          trigger: "blur",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入密码",
          trigger: "blur",
        },
      ],
    });

    const editrules = reactive({
      sname: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "blur",
        },
      ],
      age: [
        {
          required: true,
          message: "请输入年龄",
          trigger: "blur",
        },
        { type: "number", message: "类型必须为数字" },
      ],
      phone: [{ validator: checkphone, trigger: "blur" }],
      gender: [
        {
          required: true,
          message: "请选择性别",
          trigger: "blur",
        },
      ],
      position: [
        {
          required: true,
          message: "请选择职位",
          trigger: "blur",
        },
      ],
    });

    const editpassrules = reactive({
      oldpass: [
        {
          required: true,
          message: "请输入旧密码",
          trigger: "blur",
        },
      ],
      repepass: [{ validator: checkpass, trigger: "blur" }],
      newpass: [
        {
          required: true,
          message: "请输入新密码",
          trigger: "blur",
        },
      ],
    });

    onMounted(() => {
      getdata();
    });

    function getdata() {
      let page = currentPage.value;
      let size = Pagesize.value;
      getstaff().then((res) => {
        listdata.value = res.data.page.list;
        totalNumber.value = res.data.page.list.length;
        tableData.value = res.data.page.list.slice(
          page * size - size,
          page * size
        );
      });
    }

    function select(prop) {
      let name = { key: prop };
      getstaffdata(name).then((res) => {
        window.console.log(res.data.page.list);
        listdata.value = res.data.page.list;
        totalNumber.value = res.data.page.list.length;
        currentPage.value = 1;
        tableData.value = res.data.page.list.slice(0, Pagesize.value);
      });
    }

    function handleEdit(index, row) {
      editVisible.value = true;
      editform.sid = row.sid;
      editform.sname = row.sname;
      editform.phone = parseInt(row.phone);
      editform.gender = row.gender;
      editform.age = row.age;
      editform.position = row.position;
      editform.salary = parseInt(row.salary);
    }

    function handleEditPass(index, row) {
      editpassVisible.value = true;
      if(editpassform.sid!=row.sid||!editpassform.sid){
        editpassform.oldpass="";
        editpassform.repepass="";
        editpassform.newpass="";
      }
      editpassform.sid = row.sid;
    }

    function confirmpass(form){
      this.$refs.editpassFormRef.validate((valid) => {
        if (valid) {
          updatestaffpass(form).then((res) => {
            if (res.data.code == 0) {
              ElMessage({
                message: "编辑成功",
                type: "success",
              });
              

            } else if(res.data.code==15004){
              ElMessage({
                message: res.data.msg,
                type: "error",
              });

            }
          });
          editpassVisible.value = false;
        } else {
          ElMessage({
            message: "编辑表单不符合规则",
            type: "error",
          });
        }
      });

    }

    function confirmadd(form) {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          addstaffinfo(form);
        } else {
          ElMessage({
            message: "输入表单不符合规则",
            type: "error",
          });
        }
      });
    }

    function addstaffinfo(form) {
      let userinfo = { account: form.account, password: form.password };
      insertstaff(userinfo)
        .then((res) => {
          if (res.data.code == 0) {
            delete form.account;
            delete form.password;
            form.sid = res.data.sid;
            addstaff(form);
          } else if (res.data.code == 15001) {
            ElMessage({
              message: "用户名重复",
              type: "error",
            });
          }
        })
        .catch(function (err) {
          ElMessage({
            message: "错误原因:" + err,
            type: "error",
          });
        });
      dialogVisible.value = false;
    }

    function addstaff(form) {
      savestaff(form)
        .then((res) => {
          if (res.data.code == 0) {
            ElMessage({
              message: "新增成功",
              type: "success",
            });
            getdata();
          } else if (res.data.code == 15001) {
            ElMessage({
              message: "用户名重复",
              type: "error",
            });
          }
        })
        .catch(function (err) {
          ElMessage({
            message: "错误原因:" + err,
            type: "error",
          });
        });
    }

    function confirmedit(form) {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          updatestaffbyid(form).then((res) => {
            if (res.data.code == 0) {
              ElMessage({
                message: "编辑成功",
                type: "success",
              });
              getdata();
            } else {
              ElMessage({
                message: "编辑失败",
                type: "error",
              });
            }
          });
          editVisible.value = false;
        } else {
          ElMessage({
            message: "编辑表单不符合规则",
            type: "error",
          });
        }
      });
    }

    function handleCurrentChange(page) {
      currentPage.value = page;
      let size = Pagesize.value;
      tableData.value = listdata.value.slice(page * size - size, page * size);
    }

    function indexMethod(index) {
      return index + 1 + (currentPage.value - 1) * Pagesize.value;
    }

    function changemult(val) {
      let ids = [];
      for (let i in val) {
        ids.push(val[i].sid);
      }
      multipleSelection.value = ids;
    }

    function alldelete(data) {
      if (data.length == 0) {
        ElMessage({
          message: "你好像没有选中删除的数据项",
          type: "warning",
        });
      } else {
        deletestaffbyid(data).then((res) => {
          if (res.data.code == 0) {
            ElMessage({
              message: "删除成功",
              type: "success",
            });
            getdata();
          } else {
            ElMessage({
              message: "删除失败",
              type: "error",
            });
          }
        });
      }
    }

    function handleDelete(index, row) {
      //删除操作
      let shid = [row.sid];

      deletestaffbyid(shid).then((res) => {
        if (res.data.code == 0) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          getdata();
        } else {
          ElMessage({
            message: "删除失败",
            type: "error",
          });
        }
      });
    }

    return {
      input1,
      tableData,
      multipleSelection,
      dialogVisible,
      editpassVisible,
      editVisible,
      select,
      addrules,
      editrules,
      editpassrules,
      editpassform,
      confirmadd,
      confirmpass,
      indexMethod,
      editform,
      totalNumber,
      currentPage,
      Pagesize,
      handleEdit,
      handleEditPass,
      confirmedit,
      alldelete,
      handleDelete,
      form,
      changemult,
      handleCurrentChange,
    };
  },
});
</script>
<style scoped>
.head {
  font-size: 18px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
.addform >>> .el-form-item {
  padding-left: 8%;
}
.addform >>> .el-input {
  width: 80%;
}
.pagin {
  text-align: center;
  margin-left: -10%;
}
</style>